package com.cloud.servlet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloud.core.BaseServlet;
import com.cloud.dao.ContactBean;
import com.cloud.dao.DoctorBean;
import com.cloud.dao.DoctorInfo;
import com.cloud.dao.HospitalBean;
import com.cloud.dao.InvestigatorsBean;
import com.cloud.dao.MyPatientBean;
import com.cloud.dao.PatientBean;
import com.cloud.dao.ProjectBean;
import com.cloud.dao.RatingBean;
import com.cloud.service.DoctorService;
import com.cloud.service.FileService;
import com.cloud.service.MyPatientService;
import com.cloud.service.PatientService;
import com.cloud.service.RatingService;
import com.cloud.service.UserService;
import com.cloud.util.Code;
import com.cloud.util.CommUtil;

/**
 * 1Cloud1
 * @author Administrator
 * @since 2015-11-4
 * @version 1.0 
 */
@Controller
@RequestMapping("/doctor")
public class DoctorServlet extends BaseServlet {
	private static final Logger logger = LoggerFactory.getLogger(DoctorServlet.class);
	@Autowired
	private UserService UserService;
	@Autowired
	private DoctorService DoctorService;
	@Autowired
	private FileService FileService;
	@Autowired
	private RatingService RatingService;
	@Autowired
	private PatientService PatientService;
	@Autowired
	private MyPatientService MyPatientService;
	
	/**
	 * 推荐医生
	 * @param request
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/recommend/list", method = { RequestMethod.GET})
	public @ResponseBody Object randomlist(HttpServletRequest request, DoctorBean doctor) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(doctor == null || CommUtil.isEmpty(doctor.getUserId())){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		List<DoctorInfo> retDoctorList = new ArrayList<DoctorInfo>();
		List<String> retDoctorIdList =  DoctorService.queryRandomDoctorIdList(doctor);
		if(retDoctorIdList == null){
			map.put("code", Code.C200.key);
			map.put("msg", Code.C200.desc);
			map.put("data", retDoctorList);
			return map;
		}
		logger.debug(String.format("开始查询随机推荐医生信息：ids：%s   userId[%s]", retDoctorIdList, doctor.getUserId()));
		doctor.setFrom(CommUtil.listToString(retDoctorIdList, ","));
		retDoctorList = DoctorService.queryDoctor(doctor);
		for(DoctorInfo info : retDoctorList){
			if(!CommUtil.isEmpty(info.getCrcHead()))
				info.setCrcHead(FileService.getVisitUrl(info.getCrcHead()));
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", retDoctorList);
		return map;
	}
	
	/**
	 * 查询医生
	 * @param request
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/list", method = { RequestMethod.GET})
	public @ResponseBody Object list(HttpServletRequest request, DoctorBean doctor) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(doctor == null || CommUtil.isEmpty(doctor.getUserId()) || (CommUtil.isEmpty(doctor.getUserName()) && CommUtil.isEmpty(doctor.getId()))){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		List<DoctorInfo> retDoctorList = new ArrayList<DoctorInfo>();
		logger.debug(String.format("开始查询医生信息：id[%s] name[%s]", doctor.getId(), doctor.getUserName()));
		retDoctorList = DoctorService.queryDoctor(doctor);
		for(DoctorInfo info : retDoctorList){
			if(!CommUtil.isEmpty(info.getCrcHead()))
				info.setCrcHead(FileService.getVisitUrl(info.getCrcHead()));
			if(!CommUtil.isEmpty(info.getLicense()))
				info.setLicense(FileService.getVisitUrl(info.getLicense()));
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", retDoctorList);
		return map;
	}
	
	/**
	 * 查询评分
	 * @param request
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/{doctor}/rating", method = { RequestMethod.GET})
	public @ResponseBody Object rating(HttpServletRequest request, @PathVariable String doctor) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(doctor == null || (CommUtil.isEmpty(doctor))){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		RatingBean bean = new RatingBean();
		bean.setDoc_id(doctor);
		List<RatingBean> retDoctorRatingList = new ArrayList<RatingBean>();
		logger.debug(String.format("开始查询医生[%s]评语信息", doctor));
		retDoctorRatingList = RatingService.getRatingList(bean);
		for(RatingBean info : retDoctorRatingList){
			if(!CommUtil.isEmpty(info.getHead()))
				info.setHead(FileService.getVisitUrl(info.getHead()));
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", retDoctorRatingList);
		return map;
	}
	
	/**
	 * 修改医生信息
	 * @param request
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/information/update", method = { RequestMethod.POST})
	public @ResponseBody Object dupload(HttpServletRequest request, @RequestBody DoctorBean doctor) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(doctor == null || (CommUtil.isEmpty(doctor.getId()))){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		try {
			DoctorService.updateDoctor(doctor);
		} catch (Exception e) {
			logger.error("修改医生信息失败.", e);
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	/**
	 * 获取项目
	 * @param request
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/{uid}/{clientType}/project", method = { RequestMethod.GET})
	public @ResponseBody Object project(HttpServletRequest request, @PathVariable String uid, @PathVariable String clientType) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(uid == null || CommUtil.isEmpty(uid) || CommUtil.isEmpty(clientType)){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		List<ProjectBean> retBeanList = new ArrayList<ProjectBean>();
		if(Integer.valueOf(clientType).intValue() == CommUtil.PATIENT){
			PatientBean patientBean = new PatientBean();
			patientBean.setId(uid);
			patientBean.setClientType(clientType);
			retBeanList = DoctorService.queryProjectByPatient(patientBean);
		} else {
			DoctorBean doctorBean = new DoctorBean();
			doctorBean.setId(uid);
			doctorBean.setClientType(clientType);
			retBeanList = DoctorService.queryProjectByDoctor(doctorBean);
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", retBeanList);
		return map;
	}
	
	/**
	 * 根据项目获取医院
	 * @param request
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/{proid}/hospital", method = { RequestMethod.GET})
	public @ResponseBody Object hospital(HttpServletRequest request, @PathVariable String proid) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(proid == null || CommUtil.isEmpty(proid)){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		List<HospitalBean> retBeanList = DoctorService.queryHospitalByPro(proid);
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", retBeanList);
		return map;
	}
	
	/**
	 * 根据项目/医院获取医生
	 * @param request
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/{proid}/{hospital}/doctor", method = { RequestMethod.GET})
	public @ResponseBody Object hospital(HttpServletRequest request, @PathVariable String proid, @PathVariable String hospital) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(proid == null || CommUtil.isEmpty(proid) || CommUtil.isEmpty(hospital)){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		InvestigatorsBean investigators = new InvestigatorsBean();
		investigators.setHos_id(hospital);
		investigators.setPro_id(proid);
		List<DoctorBean> retBeanList = DoctorService.queryDoctorByProHos(investigators);
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", retBeanList);
		return map;
	}
	
	/**
	 * 根据项目/医院获取患者
	 * @param request
	 * @param doctor
	 * @return
	 */
	@RequestMapping(value = "/{proid}/{hospital}/patient", method = { RequestMethod.GET})
	public @ResponseBody Object patient(HttpServletRequest request, @PathVariable String proid, @PathVariable String hospital) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(proid == null || CommUtil.isEmpty(proid) || CommUtil.isEmpty(hospital)){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		InvestigatorsBean investigators = new InvestigatorsBean();
		investigators.setHos_id(hospital);
		investigators.setPro_id(proid);
		List<PatientBean> retBeanList = DoctorService.queryPatientByProHos(investigators);
		List<Map<String, String>> _mapList = new ArrayList<Map<String, String>>();
		for(PatientBean _patient : retBeanList){
			Map<String, String> _map = new HashMap<String, String>();
			_map.put("id", _patient.getId());
			_map.put("userName", _patient.getUserName());
			_map.put("fullName", _patient.getFullname());
			_map.put("head", FileService.getVisitUrl(_patient.getCrc()));
			_map.put("note", _patient.getGender()); //备注
			_map.put("proId", _patient.getPro_id());
			_map.put("proName", _patient.getPro_name());
			_map.put("joinDate", _patient.getJoin_date());
			_map.put("createTime", _patient.getCreateTime());
			_mapList.add(_map);
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", _mapList);
		return map;
	}
	
	/**
	 * 分配项目
	 * @param request
	 * @param bean
	 * @return
	 */
	@RequestMapping(value = "/allot/project", method = { RequestMethod.POST})
	public @ResponseBody Object project(HttpServletRequest request, @RequestBody InvestigatorsBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(bean == null || CommUtil.isEmpty(bean.getDoc_id()) || CommUtil.isEmpty(bean.getPro_id()) || CommUtil.isEmpty(bean.getHos_id())){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		/*PatientBean patientBean = new PatientBean();
		patientBean.setId(bean.getHos_id());
		patientBean.setPro_id(bean.getPro_id());
		PatientService.updatePatient(patientBean); //更新patient的项目ID
		InvestigatorsBean investigators = new InvestigatorsBean();
		investigators.setDoc_id(bean.getDoc_id());
		investigators.setPro_id(bean.getPro_id());
		String crcId = DoctorService.queryCrcByDoctorProject(investigators);
		if(!CommUtil.isEmpty(crcId)){
			MyPatientBean mypatient = new MyPatientBean();
			mypatient.setDoc_id(crcId);
			mypatient.setPat_id(bean.getHos_id());
			mypatient.setPro_id(bean.getPro_id());
			mypatient.setStatus("0");
			MyPatientService.addMyPatient(mypatient); //添加联系人
		}*/
		boolean flag = allotProject(bean, false, map);
		if(!flag)
			return map;
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	/**
	 * 分配医生
	 * @param request
	 * @param bean
	 * @return
	 */
	@RequestMapping(value = "/allot/doctor", method = { RequestMethod.POST})
	public @ResponseBody Object allotdoctor(HttpServletRequest request, @RequestBody InvestigatorsBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(bean == null || CommUtil.isEmpty(bean.getCrc_id()) || CommUtil.isEmpty(bean.getDoc_id()) || CommUtil.isEmpty(bean.getHos_id()) || CommUtil.isEmpty(bean.getPro_id())){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		/*PatientBean patientBean = new PatientBean();
		patientBean.setId(bean.getHos_id());
		patientBean.setPro_id(bean.getPro_id());
		PatientService.updatePatient(patientBean); //更新patient的项目ID
		MyPatientBean mypatient = new MyPatientBean();
		mypatient.setDoc_id(bean.getDoc_id());
		mypatient.setPat_id(bean.getHos_id());
		mypatient.setPro_id(bean.getPro_id());
		mypatient.setStatus("0"); //添加联系人
		MyPatientService.addMyPatient(mypatient); */
		boolean flag = allotProject(bean, true, map);
		if(!flag)
			return map;
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	/**
	 * 删除项目中的患者
	 * @param request
	 * @param bean
	 * @return
	 */
	@RequestMapping(value = "/remove/patient", method = { RequestMethod.POST})
	public @ResponseBody Object rmpatient(HttpServletRequest request, @RequestBody MyPatientBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(bean == null || CommUtil.isEmpty(bean.getDoc_id()) || CommUtil.isEmpty(bean.getPro_id()) || CommUtil.isEmpty(bean.getPat_id())){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		MyPatientBean mypatient = new MyPatientBean();
		mypatient.setDoc_id(bean.getDoc_id());
		mypatient.setPat_id(bean.getPat_id());
		mypatient.setPro_id(bean.getPro_id());
		Integer count = MyPatientService.listCount(mypatient);
		if(count == null || count == 0){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		PatientBean patientBean = new PatientBean();
		patientBean.setId(bean.getPat_id());
		patientBean.setPro_id("-1");
		PatientService.updatePatient(patientBean); //更新patient的项目ID
		MyPatientBean _mypatient = new MyPatientBean();
		_mypatient.setPat_id(bean.getPat_id());
		_mypatient.setPro_id("-1");
		_mypatient.setHos_id("");
		MyPatientService.updateMyPatient(_mypatient);
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	private boolean allotProject(InvestigatorsBean bean, boolean isCrc, Map<String, Object> map){
		PatientBean patientBean = new PatientBean();
		patientBean.setId(bean.getHos_id());
		Integer pcount = MyPatientService.getPatientProCount(patientBean);
		if(pcount != null && pcount == 0){
			patientBean.setPro_id(bean.getPro_id());
			logger.info("========更新Patient["+bean.getHos_id()+"]Pro信息=="+bean.getPro_id());
			PatientService.updatePatient(patientBean); //更新patient的项目ID
			MyPatientBean mypatient = new MyPatientBean();
			if(!isCrc){
				InvestigatorsBean investigators = new InvestigatorsBean();
				investigators.setDoc_id(bean.getDoc_id());
				investigators.setPro_id(bean.getPro_id());
				String crcId = DoctorService.queryCrcByDoctorProject(investigators);
				if(!CommUtil.isEmpty(crcId))
					mypatient.setDoc_id(crcId);
			}
			if(isCrc)
				mypatient.setDoc_id(bean.getDoc_id());
			mypatient.setPat_id(bean.getHos_id());
			mypatient.setStatus("0");
			Integer count = MyPatientService.listCount(mypatient);
			mypatient.setPro_id(bean.getPro_id());
			mypatient.setHos_id(bean.getHospital());
			if(!CommUtil.isEmpty(mypatient.getDoc_id())){
				logger.info("========更新/添加Doc["+mypatient.getDoc_id()+"]的MyPatient["+bean.getHos_id()+"]Pro信息=="+bean.getPro_id());
				if(count != null && count > 0){
					MyPatientService.updateMyPatient(mypatient);
				} else {
					MyPatientService.addMyPatient(mypatient); //添加联系人
				}
			}
			//更新
			MyPatientBean _mypatient = new MyPatientBean(); //更新状态
			if(isCrc)
				_mypatient.setDoc_id(bean.getCrc_id());
			if(!isCrc)
				_mypatient.setDoc_id(bean.getDoc_id());
			_mypatient.setPat_id(bean.getHos_id());
			_mypatient.setPro_id(bean.getPro_id());
			_mypatient.setHos_id(bean.getHospital());
			logger.info("========更新自己Doc["+_mypatient.getDoc_id()+"]的MyPatient["+bean.getHos_id()+"]Pro信息=="+bean.getPro_id());
			MyPatientService.updateMyPatient(_mypatient);
			try {
				//更新contant表
				ContactBean cbean = new ContactBean();
				cbean.setUserId(bean.getHos_id());
				cbean.setContactId(mypatient.getDoc_id());
				Integer _count = UserService.contactsCont(cbean);
				if(_count != null &&  _count == 0){
					List<ContactBean> listContactBean = new ArrayList<ContactBean>();
					listContactBean.add(cbean);
					UserService.addUserContact(listContactBean);
				}
				cbean.setStatus("0");
				UserService.updateUserContact(cbean);
			} catch (Exception e) {
				logger.error("======", e);
			}
		} else {
			map.put("code", Code.C460.key);
			map.put("msg", Code.C460.desc);
			return false;
		}
		return true;
	}
}
